﻿using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Mvc;
using NuGet.Enterprise.Server.Models;
using NuGet.Enterprise.Server.Models.Packages;
using NuGet.Enterprise.Server.Models.Packages.BuildStore;
using NuGet.Enterprise.Server.Models.Feeds;

namespace NuGet.Enterprise.Server
{
    public static class Application
    {
        private static readonly Bootstrapper _bootstrapper = new Bootstrapper();

        internal static IKernel Kernel;

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
            DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));

            _bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            _bootstrapper.ShutDown();

            if (Kernel != null && !Kernel.IsDisposed)
            {
                Kernel.Dispose();
            }
        }


        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            Kernel = new StandardKernel();

            RegisterServices(Kernel);

            return Kernel;
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IHashProvider>().To<CryptoHashProvider>();
            kernel.Bind<IServerPackageProvider>().ToMethod(ctx => ServerPackage.GetProvider(ctx)).InRequestScope();
            kernel.Bind<IServerPackageRepository>().To<BuildStoreRepository>().InRequestScope();
            kernel.Bind<IFeedProvider>().To<FeedProvider>().InRequestScope();
            kernel.Bind<IFeedRepository>().To<FeedRepository>().InRequestScope();
        }
    }
}